#include <windows.h>
#include <shlwapi.h>
#include <stdio.h>
#pragma comment(lib,"shlwapi.lib")
#include "s4keyemu_p.h"





typedef WINUSERAPI  (WINAPI *df_API_init_emu_ef_all)
(
VOID
);


typedef WINUSERAPI  (WINAPI *df_API_un_init_emu_ef)
(
VOID
);

typedef WINUSERAPI  (WINAPI *df_API_call_EF_emu_function)
(
DWORD	dwEF_FileID,
VOID*	lpInBuffer,
DWORD	dwInBufferSize,
VOID*	lpOutBuffer,
DWORD	dwOutBufferSize,
DWORD*	lpdwRetBuffSize	
);





static HANDLE					hS4KeyEmuDLL = NULL ;
static df_API_init_emu_ef_all	lpinit_emu_ef_all = NULL ;
static df_API_un_init_emu_ef	lpun_init_emu_ef = NULL ;
static df_API_call_EF_emu_function lpcall_ef_emu_fun = NULL ;

BOOL	WINAPI	Init_S4EMU_DLL(VOID)
{	
	DWORD	dwPathLen = 0 ;

	CHAR	szCurMoudPath[MAX_PATH] = { 0 };
	CHAR	szDllFilePath[MAX_PATH] = {0 };
	
	dwPathLen = GetModuleFileNameA(NULL, szCurMoudPath, MAX_PATH);

	if( dwPathLen == 0 || dwPathLen ==_MAX_PATH)
	{
		return FALSE;
	}

	PathRemoveFileSpec(szCurMoudPath);

	wsprintfA(szDllFilePath,TEXT("%s/s4keyemu.dll"),szCurMoudPath);

	if (  hS4KeyEmuDLL )
	{
		return TRUE;
	}

	hS4KeyEmuDLL = LoadLibraryA(szDllFilePath);
	
	if ( NULL == hS4KeyEmuDLL )
	{
		return FALSE;
	}


	lpinit_emu_ef_all = (df_API_init_emu_ef_all)GetProcAddress(hS4KeyEmuDLL,"init_emu_ef_all");


	lpun_init_emu_ef = (df_API_un_init_emu_ef)GetProcAddress(hS4KeyEmuDLL,"un_init_emu_ef");


	lpcall_ef_emu_fun = (df_API_call_EF_emu_function)GetProcAddress(hS4KeyEmuDLL,"call_EF_emu_function");


	if ( NULL == lpinit_emu_ef_all || NULL == lpun_init_emu_ef || NULL == lpcall_ef_emu_fun)
	{
		FreeLibrary(hS4KeyEmuDLL);
		return FALSE;
	}
	
	if ( FALSE == lpinit_emu_ef_all() )
	{	
		FreeLibrary(hS4KeyEmuDLL);

		lpinit_emu_ef_all = NULL ;
		lpun_init_emu_ef = NULL ;
		lpcall_ef_emu_fun = NULL ;

		return FALSE;
	}
	
	
	return TRUE;
}


VOID	WINAPI	Free_S4EMU_DLL(VOID)
{	
	if (lpun_init_emu_ef)
	{
		lpun_init_emu_ef();
	}

	if (hS4KeyEmuDLL)
	{
		FreeLibrary(hS4KeyEmuDLL);

		lpinit_emu_ef_all = NULL ;
	 
 		lpun_init_emu_ef = NULL ;
 
 		lpcall_ef_emu_fun = NULL ;
	}

 	
	


	return;
}


DWORD 
WINAPI
call_e4_emu_bin
(
CHAR	szbinfileID[],
VOID*	lpInBuffer,
DWORD	dwInBufferSize,
VOID*	lpOutBuffer,
DWORD	dwOutBufferSize,
DWORD*	lpdwRetBuffSize		
)
{	
	DWORD	dwFileID = 0 ;

	if (1 != sscanf(szbinfileID,"%x",&dwFileID) )
	{
		return 0x02;
	}
	

	return lpcall_ef_emu_fun(dwFileID,lpInBuffer,dwInBufferSize,lpOutBuffer,dwOutBufferSize,lpdwRetBuffSize);

}

